import { onMounted, onUnmounted, ref } from 'vue';

// ---- SINGLETON STATE ----
let _type = ref('');
const treeRefMove = ref(null);
let _nodeKeys = 'id';
let _nodes = ref(null);
let _nodeKeysArr = ref([]);
let _nodeName = ref('');
let _nodeLevel = ref(1);
let _expandArr = ref([]);
const currentIndex = ref(0);
const currentNode = ref({});

// ---- METHODS ----
const getCurrentNodeIndex = data => {
  for (let i = 0; i < _nodeKeysArr.value.length; i++) {
    if (data[_nodeKeys] === _nodeKeysArr.value[i]) {
      currentIndex.value = i;
      break;
    }
  }
  _nodeName.value = data.label;
  _nodeLevel.value = handlerLevel(data.id);
  currentNode.value = data;
  tagStatus();
};

const mouseMoveFunc = event => {
  event.preventDefault();
  event.stopPropagation();
  let activeIndex = Number(
    JSON.parse(sessionStorage.getItem('activeIndex'))?.docker,
  );
  if (activeIndex !== 1) {
    const _currentNode = treeRefMove.value.getCurrentNode();
    if (_currentNode) {
      if (event.key === 'ArrowDown') {
        mouseDownFunc(treeRefMove.value.store.nodesMap, _nodeKeysArr.value);
      } else if (event.key === 'ArrowUp') {
        mouseUpFunc(treeRefMove.value.store.nodesMap, _nodeKeysArr.value);
      }
      _nodeName.value = currentNode.value?.label;
      _nodeLevel.value = handlerLevel(currentNode.value?.id);
      tagStatus();
    }
  }
};

const mouseUpFunc = (nodes, nodeKeys) => {
  if (currentIndex.value - 1 === -1) {
    currentIndex.value = nodeKeys.length;
  }
  for (let i = currentIndex.value - 1; i >= 0; i--) {
    if (nodes[nodeKeys[i]].canFocus) {
      treeRefMove.value.setCurrentKey(nodeKeys[i], true);
      currentIndex.value = i;
      currentNode.value = nodes[nodeKeys[i]].data;
      break;
    }
  }
};

const mouseDownFunc = (nodes, nodeKeys) => {
  if (currentIndex.value + 1 === nodeKeys.length) {
    currentIndex.value = -1;
  }
  for (let i = currentIndex.value + 1; i < nodeKeys.length; i++) {
    if (nodes[nodeKeys[i]].canFocus) {
      treeRefMove.value.setCurrentKey(nodeKeys[i], true);
      currentIndex.value = i;
      currentNode.value = nodes[nodeKeys[i]].data;
      break;
    }
  }
};

const tagStatus = () => {
  const keys = [
    'currentIndex',
    'currentNode',
    '_nodeLevel',
    '_nodeName',
    '_expandArr',
  ];
  const values = [
    currentIndex.value,
    currentNode.value,
    _nodeLevel.value,
    _nodeName.value,
    _expandArr.value,
  ];
  keys.forEach((item, index) => {
    let Obj = sessionStorage.getItem(item)
      ? JSON.parse(sessionStorage.getItem(item))
      : {};
    Obj[_type.value] = values[index];
    sessionStorage.setItem(item, JSON.stringify(Obj));
  });
};

const tagSingleStatus = (single, value) => {
  let tempSingle = JSON.parse(sessionStorage.getItem(single));
  if (tempSingle) {
    tempSingle[_type.value] = value;
    sessionStorage.setItem(single, JSON.stringify(tempSingle));
  } else {
    tempSingle = {};
    tempSingle[_type.value] = value;
    sessionStorage.setItem(single, JSON.stringify(tempSingle));
  }
};

const getTagStatus = () => {
  const keys = [
    'currentIndex',
    'currentNode',
    '_nodeLevel',
    '_nodeName',
    '_expandArr',
  ];
  const values = [currentIndex, currentNode, _nodeLevel, _nodeName, _expandArr];
  keys.forEach((item, index) => {
    let Obj = sessionStorage.getItem(item)
      ? JSON.parse(sessionStorage.getItem(item))
      : {};
    values[index]['value'] = Obj[_type.value]
      ? Obj[_type.value]
      : values[index]['value'];
  });
};

const removeStatus = () => {
  const keys = [
    'currentIndex',
    'currentNode',
    '_nodeLevel',
    '_nodeName',
    '_expandArr',
  ];
  keys.forEach((item, index) => {
    let Obj = sessionStorage.getItem(item)
      ? JSON.parse(sessionStorage.getItem(item))
      : {};
    delete Obj[_type.value];
    sessionStorage.setItem(item, JSON.stringify(Obj));
  });
};

const initMouseMove = (ref, nodeKeys) => {
  treeRefMove.value = ref;
  let initNodes = Object.keys(treeRefMove.value.store.nodesMap);
  treeRefMove.value.setCurrentKey(initNodes[0], true);
  currentNode.value = treeRefMove.value.getCurrentNode();
  _nodeName.value = currentNode.value?.label;
  getTagStatus();
  treeRefMove.value.setCurrentKey(currentNode.value?.id, true);
  treeRefMove.value.el$.removeEventListener('keydown', mouseMoveFunc);
  treeRefMove.value.el$.addEventListener('keydown', mouseMoveFunc);
};

const handlerLevel = id => {
  let level = null;
  if (id.indexOf('s-') === 0) {
    level = 1;
  } else if (id.indexOf('c-') === 0) {
    level = 2;
  } else {
    level = 3;
  }
  return level;
};

// ---- SINGLETON EXPORT ----
export function useMouseMoveByTree() {
  return {
    initMouseMove,
    currentIndex,
    currentNode,
    _nodeKeysArr,
    getCurrentNodeIndex,
    handlerLevel,
    tagSingleStatus,
    removeStatus,
    tagStatus,
    _nodeName,
    _nodeLevel,
    _nodes,
    _expandArr,
    _type,
    treeRefMove,
  };
}

// 通用表格行双击事件处理
/**
 * 通用表格行双击事件
 * @param {Object} params
 * @param {Object} params.arg - 行数据
 * @param {string} params.type - 类型（如 'vm', 'docker', 'sandbox', 'vpc'）
 * @param {string} params.idKey - 行数据的主键字段名（如 'id', 'ID'）
 * @param {string} params.expandKey - 需要展开的父节点字段名（如 'computerID', 'clusterID'）
 * @param {string} params.sessionKey - sessionStorage 记忆的 key（如 'vm', 'docker', 'sandbox', 'vpc'）
 * @param {Ref} params._nodeLevel - 节点层级 ref
 * @param {Ref} params._nodeName - 节点名称 ref
 * @param {Ref} params.currentNode - 当前节点 ref
 * @param {Ref} params._expandArr - 展开数组 ref
 * @param {Ref} params._type - 类型 ref
 * @param {Ref} params.treeRefMove - 树组件 ref
 * @param {Function} params.tagStatus - 状态同步函数
 */
export function handleTableRowDblClick({
  arg,
  type,
  idKey = 'id',
  expandKey = 'computerID',
  sessionKey = 'vm',
  _nodeLevel,
  _nodeName,
  currentNode,
  _expandArr,
  _type,
  treeRefMove,
  tagStatus,
}) {
  // 先置空再赋值，确保主页面 v-if 能感知到变化
  if (_nodeLevel) _nodeLevel.value = null;
  setTimeout(() => {
    if (_nodeLevel) _nodeLevel.value = 3;
    if (_nodeName) _nodeName.value = arg.name;
    if (currentNode)
      currentNode.value = { ...arg, id: 'v-' + (arg[idKey] ?? arg.ID) };
    if (_expandArr)
      _expandArr.value = [
        'c-' + (arg[expandKey] ?? arg.computerID ?? arg.clusterID),
      ];
    if (_type) _type.value = type;

    setTimeout(() => {
      const vmNodeId = 'v-' + (arg[idKey] ?? arg.ID);
      if (treeRefMove && treeRefMove.value) {
        treeRefMove.value.setCurrentKey(vmNodeId, true);
        // 滚动到指定位置
        let element = document.querySelector(`[data-key='${vmNodeId}']`);
        element?.scrollIntoView({
          behavior: 'smooth',
          block: 'nearest',
          inline: 'nearest',
        });
      }
    }, 300);

    if (tagStatus) tagStatus();
    let indexObj = JSON.parse(sessionStorage.getItem('activeIndex')) || {};
    indexObj[sessionKey] = 0;
    sessionStorage.setItem('activeIndex', JSON.stringify(indexObj));
  });
}
